const $_cfg = require('../config');
var net = {
    //请求地址
    _cfg: $_cfg,
    requestUrl: $_cfg.net.requesturl.default,
    //请求接口
    requestApi: function (u, d, callBack, link) {
        var _this = this;
        for (var k in d) {
            if (Array.isArray(d[k]) || Object.prototype.toString.call(d[k]) === '[object Object]') {
                d[k] = Encode(d[k]);
            }
            u
        }
        var keys = {
            Platform: $_cfg.net.platform,
            Token: wx.getStorageSync($_cfg.net.storagename),
            Sign: _this.Sign(d),
            Interface: u
        }
        keys['Sign'] = _this.Sign(keys);
        wx.request({
            /*发送数据请求*/
            header: {
                'content-type': 'application/x-www-form-urlencoded',
                Secretkey: wx.$to_encodeBase64(wx.$to_encode(keys))
            },
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            url: link == undefined ? this.requestUrl : link,
            data: d,
            method: 'POST',
            dataType: 'json',
            success: function (res) {
                callBack(res.data);
            },
            fail: function (res) {
                console.log(res)
            }
        });
    },
    //修改请求地址
    changeRequest: function (l) {
        var _this = this;
        var u = $_cfg.net.requesturl;
        Object.getOwnPropertyNames(u).forEach(function (k) {
            if (k == l) {
                _this.requestUrl = u[k];
                return;
            }
        });
        // this.requestUrl = l;
    },
    /*
     * 参数签名
     * @param array parames 待代签名的参数集
     * @return string
     */
    Sign: function (d) {
        var signSrc = '';
        for (var k in d) {
            if (signSrc == '') {
                signSrc = signSrc + k + '=' + d[k];
            } else {
                signSrc = signSrc + '&' + k + '=' + d[k];
            }
        }
        signSrc = signSrc + '&key=' + $_cfg.net.sha1key;
        return wx.$to_sha1(signSrc);
    }
}
module.exports = net;